import api from './api';
import { ListItemType, CommentType } from '../types/index';

const extractImageSrc = (htmlString: string) => {
  // 正则表达式匹配 src="" 中是图片的内容
  const regex = /src="(https:\/\/[^"]+\.(jpg|jpeg|png|gif|svg))"/i;
  const match = htmlString.match(regex);

  // 如果有匹配，返回第一个匹配的图片地址
  return match ? match[1] : null;
}

// 置顶处理函数
const sortedArray = (list=[]) => {
  return list.sort((a, b) => {
    // 判断是否包含sticky字段
    const aHasSticky = a.sticky ? 1 : 0;
    const bHasSticky = b.sticky ? 1 : 0;
    // 将包含sticky的项排到顶部
    return bHasSticky - aHasSticky;
  });
}

// 获取文章列表并格式化数据
const handleArticleList = async (params, isSort = false) => {
  let res = await api.getArticleList(params);
  if (Array.isArray(res)) {
    // 置顶数据处理
    if (isSort) {
      res = sortedArray(res);
    }
    // 等待所有的评论请求完成
    return Promise.all((res as ListItemType[]).map(processArticle));
  }
}

// 处理每篇文章的评论
const processArticle = async (item) => {
  // 文章id 获取评论数量
  const comments = await api.getComments({ post: item.id });
  const cleanedExcerpt = item.excerpt.rendered.replace(/&hellip;|\[.*?\]/g, '');
  // 图片地址
  const imageUrl = extractImageSrc(item.content.rendered);
  // 将评论数量添加到对应的文章对象中
  return {
    ...item,
    commentCount: (comments as CommentType[]).length,
    excerpt: { rendered: cleanedExcerpt },
    date: transformDate(item.date),
    imageUrl
  };
}

// 时间转化 2024年10月23日
const transformDate = (dateString: string) => {
  // 获取格式化后的日期
  const formattedDate = new Date(dateString).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric'});
  // 替换月份为数字
  return formattedDate.replace(/(\d{4})年(\d{1,2})月/, '$1年$2月');
}

// 显示消息提示
const showToast = (message, icon: "none" | "success" | "fail" | "exception" | "loading" = "none", success?: () => void ) => {
  const duration = 1500;
  my.showToast({
    type: icon,
    content: message,
    duration,
    success: () => {
      setTimeout(()=>{
        success && success();
      }, duration)
    }
  });
};
// 评论数据处理
const organizeComments = (comments=[]) => {
  const map = {};
  const result = [];
  comments.forEach(comment => {
    const formattedDate = comment.date.replace('T', ' ');
    map[comment.id] = { ...comment, date: formattedDate, children: [] };
  });
  comments.forEach(comment => {
    if (comment.parent) {
      map[comment.parent].children.push(map[comment.id]);
    } else {
      result.push(map[comment.id]);
    }
  });  
  addContentToDeepChildren(result);
  return result;
}
// 递归遍历并处理每个对象
const addContentToDeepChildren = (arr, authorName?: string, level = 0) => {
  arr.forEach((item) => {
    // 当 level 达到 2（即三级）时，添加内容
    if (level >= 2) {
      const content = item.content.rendered.replace(/\<p/gi, '<p class="multi-reply-content" ');
      item.content.rendered = `<p class="multi-reply">回复<span class="multi-reply-authorName">${authorName}</span>:&ensp;${content}</p>`;
    }

    // 如果有 children，则递归调用
    if (item.children) {
      addContentToDeepChildren(item.children, item.author_name, level + 1);
    }
  });
}
// rich-text 不支持 figure 标签
const handleArticleImg = (htmlString) => {
  // 去除 figure 标签
  htmlString = htmlString.replace(/<figure[^>]*>(.*?)<\/figure>/s, '$1')
  // img 加行内样式
  return htmlString.replace(/<img([^>]*)\/?>/g, (match, group1) => {
    return `<img${group1} style="display:block;width:100%;height:auto;" />`;
  });
}

export default {
  handleArticleList,
  transformDate,
  showToast,
  organizeComments,
  sortedArray,
  handleArticleImg
}
